package net.slowpoison.loveclock.client;

public class Digit {
	private static final int DIA = Ticker.getDia();
	private static final int SEP = Ticker.getSep();
	
	private static int[][] bitmap = new int[][] {
			new int[]{ 0xf, 0x9, 0x9, 0x9, 0x9, 0x9, 0xf }, // 0
			new int[]{ 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }, // 1
			new int[]{ 0xf, 0x1, 0x1, 0xf, 0x8, 0x8, 0xf }, // 2
			new int[]{ 0xf, 0x1, 0x1, 0xf, 0x1, 0x1, 0xf }, // 3
			new int[]{ 0x9, 0x9, 0x9, 0xf, 0x1, 0x1, 0x1 }, // 4
			new int[]{ 0xf, 0x8, 0x8, 0xf, 0x1, 0x1, 0xf }, // 5
			new int[]{ 0xf, 0x8, 0x8, 0xf, 0x9, 0x9, 0xf }, // 6
			new int[]{ 0xf, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }, // 7
			new int[]{ 0xf, 0x9, 0x9, 0xf, 0x9, 0x9, 0xf }, // 8
			new int[]{ 0xf, 0x9, 0x9, 0xf, 0x1, 0x1, 0xf }, // 9
			new int[]{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }  // blank
	};
	
//	private static int BG = 0xFF555555;
	private static int ROWS = 7;
	private static int COLS = 4;
	
	private Dot[][] dots = new Dot[ROWS][COLS];
	private int digit;
	private int x, y;
	private Dot.DotType type;
	
	public Digit(Dot.DotType type, int digit, int x, int y) {
		this.x = x;
		this.y = y;
		this.digit = digit;
		this.type = type;
		
		// create dots corresponding to digits
		for (int i=0; i < ROWS; ++i) {
			for (int j=0; j < COLS; ++j) {
				if (isBitSet(digit, i, j))
					dots[i][j] = LoveClock.borrowDot(type, x + j*(DIA+SEP), y + i*(DIA+SEP));
				else
					dots[i][j] = LoveClock.borrowDot(Dot.DotType.BG, x + j*(DIA+SEP), y + i*(DIA+SEP));
			}
		}
	}
	
	public void set(int digit) {
//		List<Dot> discardedDots = new ArrayList<Dot>();
		
		// right here, we have the old digit in this.digit and the
		// new one in digit
		for (int i=0; i < ROWS; ++i) {
			for (int j=0; j < COLS; ++j) {
				// if old bit isn't set and new bit is set
				if (!isBitSet(this.digit, i, j) && isBitSet(digit, i, j)) {
					// return the gray dot
					LoveClock.returnDot(dots[i][j]);
					// borrow a heart dot
					dots[i][j] = LoveClock.borrowDot(type, x + j*(DIA+SEP), y + i*(DIA+SEP));
					// return a gray dot
				// if old bit is set and new bit isn't set
				} else if (isBitSet(this.digit, i, j) && !isBitSet(digit, i, j)) {
					// return the heart dot to the pool
					LoveClock.returnDot(dots[i][j]);
					// borrow a gray dot
					dots[i][j] = LoveClock.borrowDot(Dot.DotType.BG, x + j*(DIA+SEP), y + i*(DIA+SEP));
				}
			}
		}
		
		// set the new digit
		this.digit = digit;
	}

	private boolean isBitSet(int d, int i, int j) {
		return ((bitmap[d][i] & (1 << (3 -j))) != 0);
	}

	public static int getWidth() {
		return COLS*(DIA + SEP) - SEP;
	}

	public static int getHeight() {
		return ROWS*(DIA + SEP) - SEP;
	}

	public int getX() {
		return x;
	}
	public int getY() {
		return y;
	}
}
